package com.cch.cooperation.api.common.sdk.umeng.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class SignUtil {

    private static final String HMAC_SHA256 = "HmacSHA256";
    private static final List<String> SIGN_HEADERS = Arrays.asList("X-Ca-Key", "X-Ca-Stage", "X-Ca-Timestamp", "X-Ca-Version");

    public static String generate(String apiPath, String httpMethod, Map<String, String> headers, String secret) throws Exception {
        // 构造签名字符串
        StringBuilder builder = new StringBuilder();
        builder.append(httpMethod.toUpperCase()).append("\n");
        builder.append(headers.get("Accept")).append("\n");
        builder.append(headers.get("Content-MD5")).append("\n");
        builder.append(headers.get("Content-Type")).append("\n\n");
        SIGN_HEADERS.forEach(header -> builder.append(header).append(":").append(headers.get(header)).append("\n"));
        builder.append(apiPath);
        String signString = builder.toString();
        // 用 HMAC-SHA256 算法
        Mac hmacSha256 = Mac.getInstance(HMAC_SHA256);
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, HMAC_SHA256));
        return new String(Base64.encodeBase64(hmacSha256.doFinal(signString.getBytes(StandardCharsets.UTF_8))));
    }

}
